
<!DOCTYPE html>
<html lang="">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <script src="/js/busuanzi.pure.mini.js" async></script>
  
  
    <meta name="keywords" content="Emberjs,Ember-Teach,Ember-Template," />
  

  
    <meta name="description" content="一个专注一coding的网站。提供丰富编程知识，包括Spring、Java、EmberJS、SpringBoot等等技术。" />
  
  
  <link rel="icon" type="image/x-icon" href="/image/favicon.ico">
  <title>表单元素 [ Keep Coding ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="/css/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.0.2"><link rel="alternate" href="/atom.xml" title="Keep Coding" type="application/atom+xml">
</head>

<body>
  <div class="nav-container">
    <nav class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <img class="avatar" src="/image/favicon.ico">
    <span class="title">Keep Coding</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/search" class="pure-menu-link">搜索</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        表单元素
      </h1>
      <span>
        
        <time class="time" datetime="2020-01-18T14:50:37.000Z">
        2020-01-18
      </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
      <span class="post-tags">
        <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Teach/" rel="tag">Ember-Teach</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Ember-Template/" rel="tag">Ember-Template</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Emberjs/" rel="tag">Emberjs</a></li></ul>
      </span>
    </span>
      <span class="slash">/</span>
      <span class="read">
      <span id="busuanzi_value_page_pv"></span> 点击
    </span>
      <span class="slash">/</span>
      <span class="read">阅读耗时 2 分钟</span>
    </header>

    <div class="post-content">
      <p>Ember提供的表单元素都是经过封装的，封装成了<code>view</code>组件。经过解析渲染之后就会生成普通的HTML标签。更多详细信息你可以查看他们的实现源码：<a target="_blank" rel="noopener" href="https://github.com/emberjs/ember.js/blob/v2.0.1/packages/ember-views/lib/views/text_field.js#L36">Ember.TextField</a>、<a target="_blank" rel="noopener" href="https://github.com/emberjs/ember.js/blob/v2.0.1/packages/ember-views/lib/views/checkbox.js#L10">Ember.Chechbox</a>、<a target="_blank" rel="noopener" href="https://github.com/emberjs/ember.js/blob/v2.0.1/packages/ember-views/lib/views/text_area.js#L8">Ember.TextArea</a>。</p>
<p>按照惯例，先创建一个<code>route</code>：<br><br><code>ember generate route form-helper</code>。</p>
<h3 id="1，input助手"><a href="#1，input助手" class="headerlink" title="1，input助手"></a>1，<code>input</code>助手</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;! //app/templates/form-helper.hbs &#125;&#125;</span><br><span class="line">&#123;&#123;input name=&quot;username&quot; placeholder=&quot;your name&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>

<p>其中可以使用在<code>input</code>助手上的属性有很多，包括<code>readonly</code>、<code>value</code>、<code>disabled</code>、<code>name</code>等等，更多有关的属性介绍请移步<a href="guides.emberjs.com/v2.0.0/templates/input-helpers/">官网介绍</a>。<br><br><strong>注意：对于使用在<code>input</code>助手上的属性是不是使用双引号括住是有区别的。比如<code>value=&#39;helloworld&#39;</code>和<code>value=helloworld</code>渲染之后的结果是不一样的，第一种写法是直接把”helloworld”这个字符串赋值设置到<code>value</code>上，第二种写法是从上下文获取变量helloworld的值再设置到<code>value</code>上，通常是在<code>controller</code>或者<code>route</code>设置的值。</strong><br>看下面2行代码的演示结果：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;input name=&quot;username&quot; placeholder=&quot;your name&quot; value=&quot;model.helloworld&quot;&#125;&#125;</span><br><span class="line"><span class="tag">&lt;<span class="name">br</span>&gt;</span><span class="tag">&lt;<span class="name">br</span>&gt;</span></span><br><span class="line">&#123;&#123;input name=&quot;username&quot; placeholder=&quot;your name&quot; value=model.helloworld&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>修改对应的<code>route</code>类，重写<code>model</code>回调，返回一个字符串；或者你可以在模板对应的<code>controller</code>类设置。比如下面的第二段代码（使用命令<code>ember generate controller form-helper</code>得到模板对应的<code>controller</code>类。<br>）。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/routes/form-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Route.extend(&#123;</span><br><span class="line">    model: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> &#123; <span class="attr">helloworld</span>: <span class="string">&#x27;The value from route...&#x27;</span> &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>在<code>controller</code>类初始化测试数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/controllers/form-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    helloworld: <span class="string">&#x27;The value from route...&#x27;</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>对应的，如果你使用的是<code>controller</code>初始化测试数据，那么你的模板获取数据的方式就要稍微修改下。需要去掉前缀<code>model.</code>。<code>controller</code>不需要在回调中初始化测试数据，可用直接定义成<code>controller</code>的属性。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;input name=&quot;username&quot; placeholder=&quot;your name&quot; value=helloworld&#125;&#125;</span><br></pre></td></tr></table></figure>

<p><img src="/content/images/2016/03/40.png" alt="运行结果"></p>
<h3 id="2，在input助手上指定触发事件"><a href="#2，在input助手上指定触发事件" class="headerlink" title="2，在input助手上指定触发事件"></a>2，在<code>input</code>助手上指定触发事件</h3><p>你可以想想下，我们平常写过的javascript代码，不是可用直接在<code>input</code>输入框上使用javascript的函数，同理的，<code>input</code>助手上可以使用javascript函数，不过使用方式有点差别，请看下面示例。比如按<code>enter</code>键触发指定的事件、失去焦点触发事件等等。<br>首先编写<code>input</code>输入框，获取<code>input</code>输入框的值有点不按常理=^=。在<code>controller</code>类获取<code>input</code>输入框的值是通过不用双引号的<code>value</code>属性获取的。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">按enter键触发</span><br><span class="line">&#123;&#123;input value=getValueKey enter=&quot;getInputValue&quot; name=getByName placeholder=&quot;请输入测试的内容&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/controllers/form-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    actions: &#123;</span><br><span class="line">        getInputValue: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> v = <span class="built_in">this</span>.get(<span class="string">&#x27;getValueKey&#x27;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;v = &#x27;</span> + v);</span><br><span class="line"></span><br><span class="line">            <span class="keyword">var</span> v2 = <span class="built_in">this</span>.get(<span class="string">&#x27;getByName&#x27;</span>);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">&#x27;v2 = &#x27;</span> + v2);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>输入测试内容后按<code>enter</code>键。</p>
<p><img src="/content/images/2016/03/41.png" alt="run result"></p>
<p>最后的输出结果有那么一点点意外。<code>v</code>的值是正确的，<code>v2</code>却是<code>undefined</code>。可见在<code>controller</code>层获取页面的值是通过<code>value</code>这个属性而不是<code>name</code>这个属性。跟我们平常HTML的<code>input</code>有点不一样了！！这个需要注意下。</p>
<h3 id="3，checkbook助手"><a href="#3，checkbook助手" class="headerlink" title="3，checkbook助手"></a>3，<code>checkbook</code>助手</h3><p><code>checkbox</code>这个表单元素也是经过Ember封装了，作为一个组件使用。使用过程需要注意的问题与前面的<code>input</code>是一样的，属性是不是使用双引号所起的作用是不一样的。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">checkbox&#123;&#123;input type=&quot;checkbox&quot; checked=isChecked &#125;&#125;</span><br></pre></td></tr></table></figure>
<p>你可以在<code>controller</code>增加一个属性<code>isChecked</code>并设置为<code>true</code>，<code>checkbox</code>将默认为选中。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// app/controllers/form-helper.js</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> Ember <span class="keyword">from</span> <span class="string">&#x27;ember&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Ember.Controller.extend(&#123;</span><br><span class="line">    actions: &#123;</span><br><span class="line">        <span class="comment">// ⋯⋯</span></span><br><span class="line">    &#125;,</span><br><span class="line">    isChecked: <span class="literal">true</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><img src="/content/images/2016/03/42.png" alt="result"></p>
<h3 id="4，textarea助手"><a href="#4，textarea助手" class="headerlink" title="4，textarea助手"></a>4，<code>textarea</code>助手</h3><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;textarea value=key cols=&quot;80&quot; rows=&quot;3&quot; enter=&quot;getValueByV&quot;&#125;&#125;</span><br></pre></td></tr></table></figure>
<p>同样的也是通过<code>value</code>属性获取输入的值。</p>
<p>本篇简单的介绍了常用的表单元素，使用的方式比较简单，唯一需要注意的是获取的输入框输入值的方式与平常使用的HTML表单元素有点差别。其他的基本上与普通的HTML表单元素没什么差别。<br><br><br>博文完整代码放在<a target="_blank" rel="noopener" href="https://github.com/ubuntuvim/my_emberjs_code">Github</a>（博文经过多次修改，博文上的代码与github代码可能又出入，不过影响不大！），如果你觉得博文对你有点用，请在github项目上给我点个<code>star</code>吧。您的肯定对我来说是最大的动力！！</p>

    </div>

      
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/2020/01/18/ember-teach/templetes/%E8%B0%83%E8%AF%95%E5%8A%A9%E6%89%8B/" rel="next" title="调试助手">
          调试助手
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/2020/01/18/ember-teach/templetes/%E7%AC%AC%E4%BA%8C%E7%AB%A0%E6%A8%A1%E6%9D%BF%E5%B0%8F%E7%BB%93/" rel="prev" title="第二章模板小结">
            第二章模板小结
          </a>
          <span>〉</span>
        
      </div>
    </div>
  
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%EF%BC%8Cinput%E5%8A%A9%E6%89%8B"><span class="toc-text">1，input助手</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%EF%BC%8C%E5%9C%A8input%E5%8A%A9%E6%89%8B%E4%B8%8A%E6%8C%87%E5%AE%9A%E8%A7%A6%E5%8F%91%E4%BA%8B%E4%BB%B6"><span class="toc-text">2，在input助手上指定触发事件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%EF%BC%8Ccheckbook%E5%8A%A9%E6%89%8B"><span class="toc-text">3，checkbook助手</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#4%EF%BC%8Ctextarea%E5%8A%A9%E6%89%8B"><span class="toc-text">4，textarea助手</span></a></li></ol>
  </div>


  </div>
</div>


<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share">

</div>
<div class="post-container">
    <article class="post">
      <div id="container"></div>
    </article>
</div>

<link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
<script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script>
<script>
var gitment = new Gitment({
  id: '表单元素', // 可选。默认为 location.href
  owner: 'ubuntuvim',
  repo: 'ubuntuvim.github.io',
  oauth: {
    client_id: '48b3df0bf4ba1743e0a3',
    client_secret: 'c6c2cec09acb5eecc9d325d56cef187264aa1e16',
  },
})
gitment.render('container')
</script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item" href="http://xcoding.tech/">首页</a> |
        <a class="bottom-item" href="http://xcoding.tech/" target="_blank">主站</a> |
        <a class="bottom-item" href="https://github.com/ubuntuvim" target="_blank">GitHub</a> |
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a> |
        <a class="bottom-item" href="https://github.com/KevinOfNeu/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
</footer>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>


  
  <!-- scripts list from theme config.yml -->
  
    <script src="/js/zepto.min.js"></script>
  


<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 给logo设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("logo");
      if (logo) {
        logo.onclick = function(event) {
          returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  



</body>
</html>
